package cn.webrx.shiro;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-06-11 8:18
 */
@Service
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private DruidDataSource ds;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取输入的账号
        String username = (String) authenticationToken.getPrincipal();
        int status = 10;
        String passwd = "";
        try {
            Connection conn = ds.getConnection();
            PreparedStatement pst = conn.prepareStatement("select passwd from db_users where uname=?");
            pst.setString(1, username);
            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
                passwd = rs.getString(1);

                if ("a".equals(username)) {
                    status = 1;//锁定
                } else if ("b".equals(username)) {
                    status = 2; //禁用
                }
            } else {
                status = 0;
            }
            rs.close();
            pst.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        if (status == 0) {
            throw new UnknownAccountException("账号不存在");
        } else if (status == 1) {
            throw new LockedAccountException("锁定");
        } else if (status == 2) {
            throw new DisabledAccountException("禁用");
        }

        //如果不是zhangshan，就认为账号不正确，返回null
        //if(!"wangwu".equals(username)){
        //    return null;
        //}
        //交由shiro判断，账号：zhangshan,密码：123456,是否与用户输入的匹配

        //return new SimpleAuthenticationInfo("wangwu","123456",getName());
        return new SimpleAuthenticationInfo(username, passwd, getName());
        //return null;
    }
}
